package com.gdk.auth.application.controller;

import com.alibaba.fastjson.JSON;
import com.gdk.auth.application.convert.AuthPermissionDTOConverter;
import com.gdk.auth.application.convert.AuthRolePermissionDTOConverter;
import com.gdk.auth.application.dto.AuthPermissionDTO;
import com.gdk.auth.application.dto.AuthRolePermissionDTO;
import com.gdk.auth.common.entity.Result;
import com.gdk.auth.domain.entity.AuthPermissionBO;
import com.gdk.auth.domain.entity.AuthRolePermissionBO;
import com.gdk.auth.domain.service.AuthPermissionDomainService;
import com.gdk.auth.domain.service.AuthRolePermissionDomainService;
import com.google.common.base.Preconditions;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * 角色权限controller
 */
@RestController
@RequestMapping("/rolePermission/")
@Slf4j
public class RolePermissionController {

    @Resource
    private AuthRolePermissionDomainService authRolePermissionDomainService;

    /**
     * 新增角色权限
     */
    @PostMapping("add")
    public Result<Boolean> add(@RequestBody AuthRolePermissionDTO authRolePermissionDTO) {
        try {
            if (log.isInfoEnabled()){ //在面对高并发可以更好性能，直接log.info会先序列化，而先判断则不会；
                log.info("RolePermissionController.add.dto:{}", JSON.toJSONString(authRolePermissionDTO));
            }
            Preconditions.checkArgument(!CollectionUtils.isEmpty(authRolePermissionDTO.getPermissionIdList()),"权限id集合不能为空");
            Preconditions.checkNotNull(authRolePermissionDTO.getRoleId(),"角色不能为空");

            AuthRolePermissionBO authRolePermissionBO = AuthRolePermissionDTOConverter.INSTANCE
                    .convertDTOToBO(authRolePermissionDTO);
            return Result.ok(authRolePermissionDomainService.add(authRolePermissionBO));
        }catch (Exception e) {
            log.error("RolePermissionController.add.dto:{}", e.getMessage(),e);
            return Result.fail("新增角色权限失败");
        }
    }

}
